<template>
  <Dialog v-model="dialogVisible" title="编辑算法">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="算法文件" prop="path">
        <!-- 文件回显 -->
        <div v-if="formData.path" class="mb-10px">
          <div class="flex items-start gap-10px p-10px bg-gray-50 rounded-6px">
            <Icon icon="ep:document" class="text-blue-500 mt-1 flex-shrink-0" />
            <div class="flex-1 min-w-0">
              <div class="text-14px text-gray-700" style="word-break: break-all; overflow-wrap: break-word;">{{ formData.path }}</div>
            </div>
            <el-button type="danger" size="small" @click="removeFile" class="flex-shrink-0">删除</el-button>
          </div>
        </div>
        
        <!-- 文件上传 -->
        <el-upload
          ref="uploadRef"
          v-model:file-list="fileList"
          :action="importUrl"
          :headers="uploadHeaders"
          :auto-upload="true"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-progress="handleUploadProgress"
          :before-upload="beforeUpload"
          :show-file-list="true"
          :multiple="false"
          drag
          class="w-full"
        >
          <Icon icon="ep:upload" />
          <div class="el-upload__text">
            {{ formData.path ? '重新上传文件' : '将文件拖到此处，或点击上传' }}
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-switch v-model="formData.enable" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as AlgorithmApi from '@/api/system/algorithm'
import { getAccessToken, getTenantId } from '@/utils/auth'

defineOptions({ name: 'PmAlgorithmForm' })
const emit = defineEmits(['success'])
const message = useMessage()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()
const uploadRef = ref()
const fileList = ref<any[]>([])
// 修复：此前使用了“用户导入”的公共上传地址导致 500（用户导入失败）。
// 改为算法自身的上传接口地址。
const importUrl = AlgorithmApi.getImportUrl()
const uploadHeaders = ref<Record<string, any>>()

const formData = ref<any>({
  id: undefined,
  name: undefined,
  remark: undefined,
  path: undefined,
  enable: 1,
  createBy: undefined,
  createTime: undefined,
  params: []
})

const formRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  remark: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  path: [{ required: true, message: '请输入路径', trigger: 'blur' }]
})

const open = (row: any) => {
  dialogVisible.value = true
  formData.value = { ...row }
  fileList.value = []
  resetForm()
}

defineExpose({ open })

const submitForm = async () => {
  const valid = await formRef.value?.validate()?.catch(() => false)
  if (!valid) return
  formLoading.value = true
  try {
    // 不选择文件时，走原更新
    await AlgorithmApi.updateAlgorithm(formData.value)
    message.success('修改成功')
    emit('success')
  } finally {
    dialogVisible.value = false
  }
}

const resetForm = async (): Promise<void> => {
  formLoading.value = false
  await nextTick()
  // 不要清空文件列表，保持回显状态
  // uploadRef.value?.clearFiles()
}


// 上传回调
const handleUploadSuccess = (response: any) => {
  // 统一判断 code 字段，非 0 则报错，不提示成功
  const code = response?.code
  if (!(code === 0 || code === '0')) {
    formLoading.value = false
    message.error(response?.msg || '上传失败')
    resetForm()
    return
  }
  const data = response?.data ?? response
  const path = (typeof data === 'string' ? data : data?.path || data?.url || data?.filename || '') || ''
  
  // 更新path，覆盖原来的文件
  formData.value.path = path
  
  // 清空文件列表，避免进度条继续显示
  fileList.value = []
  
  formLoading.value = false
  message.success('上传成功')
}

const handleUploadError = () => {
  message.error('上传失败，请重试')
}

const handleUploadProgress = () => {
  // 每次进度回调时确保请求头存在
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
}

const beforeUpload = () => {
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  return true
}

// 删除文件
const removeFile = () => {
  formData.value.path = ''
  fileList.value = []
  uploadRef.value?.clearFiles()
}
</script>


